package com.lzy.cloud.url.controller;

import com.lzy.cloud.url.dtos.ShortUrlDto;
import com.lzy.cloud.url.reponse.ShortUrlReponse;
import com.lzy.cloud.url.service.ShortUrlService;
import com.lzy.cloud.url.util.ShortUrlUtil;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.output.Result;
import com.lzy.framework.core.utils.DozerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class ShortUrlController {

    @Autowired
    private ShortUrlService shortUrlService;

    @Autowired
    private ShortUrlUtil shortUrlUtil;

    /**
     * 短地址生成
     *
     * @param url
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Result findShortUrl(@RequestBody String url) {
        String shortUrl = shortUrlUtil.generateUrl(url);
        ShortUrlDto shortUrlDto = shortUrlService.findByShortUrl(shortUrl);
        if (shortUrlDto == null) {
            shortUrlDto = new ShortUrlDto();
            shortUrlDto.setShortUrl(shortUrl);
            shortUrlDto.setFullUrl(url);
            Ensure.that(shortUrlService.insert(shortUrlDto)).isNotNull("00000002");
        }
        return new Result(DozerUtils.map(shortUrlDto, ShortUrlReponse.class));
    }

    /**
     * 短地址路由
     *
     * @param shortUrl
     * @return
     */
    @RequestMapping(value = "/routing/{url}", method = RequestMethod.GET)
    public Result routing(@PathVariable("url") String shortUrl) {
        ShortUrlDto shortUrlDto = shortUrlService.findByShortUrl(shortUrl);
        Ensure.that(shortUrlDto).isNotNull("00000003");
        Ensure.that(shortUrlDto.getStatus().equals(1) && shortUrlDto.getDeleted().equals(0)).isTrue("00000004");
        return new Result(DozerUtils.map(shortUrlDto, ShortUrlReponse.class));
    }
}
